<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="125px">
      <el-form-item prop="datasourceId" :label="$t('tenant.datasource')">
        <el-select v-model="dataForm.datasourceId" :placeholder="$t('tenant.datasource')" style="width: 100%">
          <el-option v-for="datasource in datasourceList" :key="datasource.id" :label="datasource.name" :value="datasource.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="tenantName" :label="$t('tenant.tenantName')">
        <el-input v-model="dataForm.tenantName" :placeholder="$t('tenant.tenantName')"></el-input>
      </el-form-item>
      <el-form-item prop="domain" :label="$t('tenant.domain')">
        <el-input v-model="dataForm.domain" :placeholder="$t('tenant.domainTip')"></el-input>
      </el-form-item>
      <el-form-item prop="username" :label="$t('tenant.username')">
        <el-input v-model="dataForm.username" :placeholder="$t('tenant.username')" :disabled="!!dataForm.id"></el-input>
      </el-form-item>
      <el-form-item prop="password" :label="$t('tenant.password')" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" :placeholder="$t('tenant.password')"></el-input>
      </el-form-item>
      <el-form-item prop="remark" :label="$t('tenant.remark')">
        <el-input v-model="dataForm.remark" :placeholder="$t('tenant.remark')"></el-input>
      </el-form-item>
      <el-form-item prop="status" :label="$t('tenant.status')">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">{{ $t("tenant.status0") }}</el-radio>
          <el-radio :label="1">{{ $t("tenant.status1") }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, reactive } from "vue";
import baseService from "@/service/baseService";
import { useDebounce } from "@/utils/utils";
import { IObject } from "@/types/interface";
export default defineComponent({
  setup() {
    return reactive({
      visible: false,
      datasourceList: [] as IObject,
      dataForm: {
        id: "",
        datasourceId: "",
        domain: "",
        tenantName: "",
        username: "",
        password: "",
        realName: "",
        remark: "",
        status: 1
      }
    });
  },
  computed: {
    dataRule() {
      const validatePassword = (rule: IObject, value: string, callback: (e?: Error) => any) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        callback();
      };
      return {
        username: [{ required: true, message: this.$t("validate.required"), trigger: "blur" }],
        datasourceId: [{ required: true, message: this.$t("validate.required"), trigger: "blur" }],
        tenantName: [{ required: true, message: this.$t("validate.required"), trigger: "change" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        realName: [{ required: true, message: this.$t("validate.required"), trigger: "blur" }]
      };
    }
  },
  created() {
    this.dataFormSubmitHandle = useDebounce(this.dataFormSubmitHandle);
  },
  methods: {
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataFormRef"].resetFields();
        Promise.all([this.getDataSourceList()]).then(() => {
          if (this.dataForm.id) {
            this.getInfo();
          }
        });
      });
    },
    // 获取租户数据源列表
    getDataSourceList() {
      return baseService.get("/sys/tenant/datasource/list").then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.datasourceList = res.data;
      });
    },
    // 获取信息
    getInfo() {
      baseService.get(`/sys/tenant/${this.dataForm.id}`).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        };
      });
    },
    // 表单提交
    dataFormSubmitHandle() {
      this.$refs["dataFormRef"].validate((valid: boolean) => {
        if (!valid) {
          return false;
        }
        (!this.dataForm.id ? baseService.post : baseService.put)("/sys/tenant", {
          ...this.dataForm
        }).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$message({
            message: this.$t("prompt.success"),
            type: "success",
            duration: 500,
            onClose: () => {
              this.visible = false;
              this.$emit("refreshDataList");
            }
          });
        });
      });
    }
  }
});
</script>
